package com.harboursoftware.xstorage.ac;

import java.io.Serializable;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import com.harboursoftware.xstorage.model.XUser;

/**
 * 表示授权，则向某个授权对象（{@link Grantee}）赋予某种权限（{@link Permission}）。
 * 
 * 
 * @since 0.1
 * @author Simon Leung
 * @see Grantee
 * @see Permission
 */
public class Grant implements Serializable {
    private Grantee grantee;
    private Permission grantedPermission;

    public Grant() {
    }

    public Grant(Grantee grantee, Permission grantedPermission) {
        this.grantee = grantee;
        this.grantedPermission = grantedPermission;
    }

    public boolean checkPermission(XUser user, Permission permission) {
        if (!grantee.contains(user)) {
            return false;
        }

        if (grantedPermission == Permission.FULL_CONTROL) {
            return true;
        }

        if (grantedPermission == permission) {
            return true;
        }

        return false;
    }

    public String toXML() {
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("<Grant>");
        strBuilder.append(grantee.toXML());
        strBuilder.append("<Permission>");
        strBuilder.append(grantedPermission);
        strBuilder.append("</Permission>");
        strBuilder.append("</Grant>");
        return strBuilder.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public String toString() {
        return "Grant [grantedPermission=" + grantedPermission + ", grantee=" + grantee + "]";
    }

    public Grantee getGrantee() {
        return grantee;
    }

    public void setGrantee(Grantee grantee) {
        this.grantee = grantee;
    }

    public Permission getPermission() {
        return grantedPermission;
    }

    public void setPermission(Permission permission) {
        this.grantedPermission = permission;
    }
}
